package com.cupdata.zicon.jdk7concurrent.chapter4;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Java recommends the utilization of ScheduledThreadPoolExecutor only for
 * scheduled tasks.
 * 
 * You can change this behavior using the
 * setExecuteExistingDelayedTasksAfterShutdownPolicy() method of the
 * ScheduledThreadPoolExecutor class. With false, at the time of shutdown(),
 * pending tasks won't get executed.
 * 
 * @author SunYabing
 *
 */
public class RunTaskAfterADelay {

	public RunTaskAfterADelay() {

	}

	public static void main(String[] args) {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		System.out.printf("Main: Starting at: %s\n", new Date());
		for (int i = 0; i < 5; i++) {
			Task11 task = new Task11("Task " + i);
			executor.schedule(task, i + 1, TimeUnit.SECONDS);
			// each task will wait for a number of seconds (TimeUnit.SECONDS)
			// equal to its
			// position in the array of tasks plus one.
		}

		executor.shutdown();
		try {
			executor.awaitTermination(1, TimeUnit.DAYS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.printf("Main: Ends at: %s\n", new Date());
	}

}

class Task11 implements Callable<String> {

	private String name;

	public Task11(String name) {
		this.name = name;
	}

	@Override
	public String call() throws Exception {
		System.out.printf("%s: Starting at : %s\n", name, new Date());
		return "Hello, world";
	}
}
